﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Toolbox
{
    public partial class IpScanForm : Form
    {
        public IpScanForm()
        {
            InitializeComponent();
        }

        private void IpScanForm_Load(object sender, EventArgs e)
        {
            // 获取本机名称
            string localName = Dns.GetHostName();
            textBox1.Text = localName;

            // 获取所有IP地址
            IPAddress[] ips = Dns.GetHostAddresses(localName);
            string localIp = "127.0.0.1";
            foreach(IPAddress ip in ips)
            {
                if (!ip.IsIPv6SiteLocal)
                {
                    localIp = ip.ToString();
                }
            }
            textBox2.Text = localIp;

            char[] separator = { '.' };
            string[] array = localIp.Split(separator, StringSplitOptions.RemoveEmptyEntries);

            string beginIp = array[0] + "." + array[1] + "." + array[2] + ".1";
            textBox6.Text = beginIp;
            string endIp = array[0] + "." + array[1] + "." + array[2] + ".254";
            textBox4.Text = endIp;

        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 扫描按钮
            char[] separator = { '.' };

            string beginIp = textBox6.Text;
            string[] array = beginIp.Split(separator, StringSplitOptions.RemoveEmptyEntries);
            string startPart = array[0] + "." + array[1] + "." + array[2] + ".";
            int begin = int.Parse(array[3]);

            string endIp = textBox4.Text;
            int end = int.Parse(endIp.Split(separator, StringSplitOptions.RemoveEmptyEntries)[3]);
            try
            {
                for (int i = begin; i <= end; i++)
                {
                    string ip = startPart + i;
                    IPHostEntry host = Dns.GetHostEntry(ip);
                    string line = "IP地址：" + ip + "，主机名：" + host.HostName + Environment.NewLine;
                    textBox3.AppendText(line);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            
        }
    }
}
